/**
* @Description: 默认请求实例
* @Author: luhan
* @Date: 2021/04/07 17:08:15
* @export {Object} axios实例
* @example axios.request(config)
*          axios.get(url[, config])
*          axios.delete(url[, config])
*          axios.head(url[, config])
*          axios.post(url[, data[, config]])
*          axios.put(url[, data[, config]])
*          axios.patch(url[, data[, config]])
*/
// import { encryptParams, decryptParams, RASKEY } from './crypto';
import loading from './loading';
import ERRORMESSAGE from '../config/ErrorMessage.json';

// 加密接口前缀
const ENCRYPTEDINTERFACES = ['/app/', '/user/'];
//  含有token接口前缀
const INTERFACESWITHTOKEN = ['/app/'];

function beInculuedEncryptedInterfaces(url) {
  for (let index = 0; index < ENCRYPTEDINTERFACES.length; index += 1) {
    let item = ENCRYPTEDINTERFACES[index];
    if (url.startsWith(item)) {
      return true;
    }
  }
  return false;
}

function beInculuedInterfaceswithtoken(url) {
  for (let index = 0; index < INTERFACESWITHTOKEN.length; index += 1) {
    let item = INTERFACESWITHTOKEN[index];
    if (url.startsWith(item)) {
      return true;
    }
  }
  return false;
}

/**
* @Description: 状态码处理
* @Author: luhan
* @Date: 2021/04/08 11:40:10
* @param {String} code 状态码
* @return {Boolean} true 成功请求 false 异常请求
*/

// TODO: 错误处理
function statusCodeHandle(code, header) {
  switch (code) {
    case '00':
      return true;
    case '01':
      alert(header.message);
      return false;
    case '02':
      alert(header.message);
      return false;
    case '03':
      alert(header.message);
      return false;
    case '04':
      alert(header.message);
      return false;
    case '99':
      if (header.message.startsWith('人力资源系统')) {
        return false;
      }
      alert(header.message);
      return false;
    default:
      return false;
  }
}

/**
* @Description: 基于axios创建的实例，进行初始化操作
* @Author: luhan
* @Date: 2021/04/08 11:40:10
* @param {Object} config 配置文件
*/
const instance = this.axios.create({
  showLoading: true, // 是否展示loading框，默认开启
  baseURL: `${window.location.origin}${process.env.VUE_APP_PATH}`, // 接口地址
  timeout: 60000, // 超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

function getStatus(response) {
  return response.status || -1;
}

function errorMessageHandle(error) {
  if (error && error instanceof Error) {
    const status = getStatus(error.response);
    switch (status) {
      case 400:
        return ERRORMESSAGE.NETWORK400;
      case 404:
        return ERRORMESSAGE.NETWORK404;
      case 500:
        return ERRORMESSAGE.NETWORK500;
      default:
        return ERRORMESSAGE.OTHERERROR;
    }
  } else {
    return ERRORMESSAGE.CANNOTPARSEERRORPARAMS;
  }
}

// 请求拦截器
instance.interceptors.request.use((config) => {
  let conf = Object.create(config);
  // loading 处理
  if (conf.showLoading) {
    loading.show();
  }
  // token
  if (beInculuedInterfaceswithtoken(conf.url)) {
    // conf.headers.token = '';
    // conf.headers.userId = '';
  }
  // 加密
  if (beInculuedEncryptedInterfaces(conf.url)) {
    // conf.headers.interceptor = RASKEY;
    // conf.data.token = conf.headers.token;
    // conf.dataUnEncrypted = conf.data;
    // conf.data = encryptParams(conf.data);
  }
  return conf;
}, (error) => {
  if (error.config.showLoading) {
    loading.hide();
  }
  alert(errorMessageHandle(error));
  return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use((response) => {
  let resp = { ...response };
  const { config, data } = resp;
  // loading 处理
  if (config.showLoading) {
    loading.hide();
  }
  if (!data || !data.header) {
    alert(ERRORMESSAGE.RESPONSEHEADERERROR);
    return null;
  }
  const statusCode = data.header.statusCode.substr(0, 2);
  // 状态码处理
  if (statusCodeHandle(statusCode, data.header)) {
    // 解密;
    // if (beInculuedEncryptedInterfaces(config.url)) {
    //   resp.data.body = decryptParams(resp.data.body);
    // }
    return resp.data.body;
  }
  return null;
}, (error) => {
  // loading 处理
  if (error.config.showLoading) {
    loading.hide();
  }
  alert(errorMessageHandle(error));
  return Promise.reject(error);
});

export default instance;
